﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using LuxDiner.Model.Members;
namespace LuxDiner.Command.Members
{
    public class CustomerCommand
    {
        public static CustomerModel CreateNew(CustomerModel model)
        {
            if (model != null)
            {
                using (DBCentre db = new DBCentre())
                {
                    SaveCheck(model, db);
                    var data = Convertor.ConvertFrom<customer, CustomerModel>(model);
                    var catids = model.Categories.Select(p => p.ID).ToArray();
                    var categories = db.DataContext.customer_categories.Where(p => catids.Contains(p.ID)).ToList();
                    data.customer_categories = categories;

                    db.DataContext.customers.Add(data);
                    db.DataContext.SaveChanges();
                    model.ID = data.ID;
                }
            }
            return null;
        }

        public static void Update(CustomerModel model)
        {
            if (model != null && model.ID > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var data = db.DataContext.customers.FirstOrDefault(p => p.ID == model.ID);
                    if (data != null)
                    {
                        SaveCheck(model, db);
                        if (db.DataContext.order_deal.Any(p => p.CustomerID == model.ID) || db.DataContext.order_paid.Any(p => p.CustomerID == model.ID))
                        {
                            if (model.CType != data.CType)
                                throw new Utils.LuxDinerException("这个客户已有单据记录，不能修改类型。");
                        } //如果客户有单据记录 不能修改类型
                        Convertor.UpdateValue(model, data);
                        data.customer_categories.Clear();
                        var catids = model.Categories.Select(p => p.ID).ToArray();
                        var categories = db.DataContext.customer_categories.Where(p => catids.Contains(p.ID)).ToList();
                        data.customer_categories = categories;
                        db.DataContext.SaveChanges();
                    }
                }
            }
        }

        private static void SaveCheck(CustomerModel model, DBCentre db)
        {
            if (string.IsNullOrEmpty(model.Corporation))
                throw new ApplicationException("请输入公司名称。");
            if (string.IsNullOrEmpty(model.RealName))
                throw new ApplicationException("请输入姓名。");
            if (model.Categories == null || model.Categories.Count == 0)
                throw new ApplicationException("请为客户指定分类");
            if (db != null)
            {
                if (db.DataContext.customers.Any(p=>p.CustomerNo==model.CustomerNo && p.ID!=model.ID))
                    throw new ApplicationException("重复的客户编码。");
                if (db.DataContext.customers.Any(p => p.Corporation == model.Corporation && p.Mobile==model.Mobile && p.ID != model.ID))
                    throw new ApplicationException("重复的客户，请检查。");
            }
        }

        public static CustomerModel GetModel(int id)
        {
            if (id > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    var data = db.DataContext.customers.FirstOrDefault(p => p.ID == id);
                    if (data != null)
                    {
                        var model = Convertor.ConvertTo<CustomerModel, customer>(data);
                        if (data.customer_categories != null && data.customer_categories.Count() > 0)
                            model.Categories = Convertor.ConvertCollection<CustomerCategoryModel, customer_categories, CustomerCategoryCollection>(data.customer_categories);
                        return model;
                    }
                }
            }
            return null;
        }

        public static CustomerCollection GetCustomers(CustomerQuery sea)
        {
            var result = new CustomerCollection();
            using (DBCentre db = new DBCentre())
            {
                IQueryable<customer> q = db.DataContext.customers;
                if (sea != null)
                {
                    if (sea.CType > 0)
                        q = q.Where(p => p.CType == sea.CType);
                    if (!string.IsNullOrEmpty(sea.Key))
                        q = q.Where(p => p.Corporation.Contains(sea.Key) || p.RealName == sea.Key || p.Mobile == sea.Key || p.Pinyin.Contains(sea.Key));
                    if (!string.IsNullOrEmpty(sea.Categories)){
                        var cats = sea.Categories.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (cats.Length > 0)
                        {
                            var ids = cats.Select(p => int.Parse(p)).ToArray();
                            q = q.Where(p => p.customer_categories.Any(o => ids.Contains(o.ID)));
                        }
                    }
                    if (sea.Status > 0)
                        q = q.Where(p => p.Status == sea.Status);
                }
                var n = q.Count();
                if (n > 0)
                {
                    q = q.OrderBy(p => p.CustomerNo);
                    if (sea != null && sea.PageSize > 0)
                        q = q.Skip(sea.PageSize * sea.PageIndex).Take(sea.PageSize);
                    var lst = q.ToList();
                    result = Convertor.ConvertCollection<CustomerModel, customer, CustomerCollection>(lst);
                    result.TotalRecordsCount = n;
                    if (sea != null)
                    {
                        foreach (var m in result)
                        {
                            if (sea.GetCategories)
                            {
                                var d = lst.Find(p => p.ID == m.ID);
                                if (d.customer_categories!=null && d.customer_categories.Count>0)
                                    m.Categories = Convertor.ConvertCollection<CustomerCategoryModel, customer_categories, CustomerCategoryCollection>(d.customer_categories);
                            }
                        }
                    }
                }
            }
            return result;
        }

        public static void Delete(int id)
        {
            if (id > 0)
            {
                using (DBCentre db = new DBCentre())
                {
                    db.Delete<customer>(p => p.ID == id);
                    db.DataContext.SaveChanges();
                }
            }
        }
    }
}
